<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<link rel="stylesheet" href="./css/ol.css" type="text/css">
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			.map {
				height: 100vw;
				width: 100vw;
				position: fixed;
				top: 120rpx;
			}
		</style>
		<script src="./js/ol.js"></script>
		<!-- <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.15.1/build/ol.js"></script> -->
		<script src="./js/proj4.js"></script>
		<title>种植信息</title>
	</head>
	<body>
		<div id="map" class="map"></div>
		<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.1.js">
		</script>
		<script type="text/javascript">
			// var map = new ol.Map({
			//     target: 'map',
			//     layers: [
			//         new ol.layer.Tile({
			//             source: new ol.source.OSM()
			//         })
			//     ],
			//     view: new ol.View({
			//         center: ol.proj.fromLonLat([37.41, 8.82]),
			//         zoom: 4
			//     })
			// });
			// console.log(getQuery('data')); //获取 uni-app 传来的值

			//取url中的参数值
			function getQuery(name) {
				// 正则：[找寻'&' + 'url参数名字' = '值' + '&']（'&'可以不存在）
				let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				let r = window.location.search.substr(1).match(reg);
				if (r != null) {
					// 对参数值进行解码
					return JSON.parse(decodeURIComponent(r[2]));
				}
				return null;
			}
			// 注册4490坐标系
			proj4.defs("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs");
			ol.proj.proj4.register(proj4);

			const projection_4490 = new ol.proj.Projection({
				code: 'EPSG:4490',
				units: 'degrees',
				axisOrientation: 'neu'
			});

			projection_4490.setExtent([-180, -90, 180, 90])
			projection_4490.setWorldExtent([-180, -90, 180, 90])
			ol.proj.addProjection(projection_4490)
			ol.proj.addCoordinateTransforms('EPSG:4326', 'EPSG:4490',
				function(coordinate) {
					return proj4('EPSG:4326', 'EPSG:4490', coordinate)
				},
				function(coordinate) {
					return proj4('EPSG:4490', 'EPSG:4326', coordinate)
				}
			)

			const resolutions_4490 = [
				1.40625,
				0.703125,
				0.3515625,
				0.17578125,
				0.087890625,
				0.0439453125,
				0.02197265625,
				0.010986328125,
				0.0054931640625,
				0.00274658203125,
				0.001373291015625,
				6.866455078125e-4,
				3.4332275390625e-4,
				1.71661376953125e-4,
				8.58306884765625e-5,
				4.291534423828125e-5,
				2.1457672119140625e-5,
				1.0728836059570312e-5,
				5.364418029785156e-6,
				2.682209064925356e-6,
				1.3411045324626732e-6,
				6.705522662313365e-7,
			];


			const fxpcSatelliteLayer = new ol.layer.Tile({
				source: new ol.source.XYZ({
					url: 'https://fxpc.mem.gov.cn/data_preparation/a12eadf6-1a57-43fe-9054-2e22277bd553/4eb4b664-5633-4ab3-b0fd-345829dd3a87/wmts?layer=img&style=default&tileMatrixSet=c&service=wmts&request=gettile&version=1.0.0&format=tiles&tileMatrix={z}&tileCol={x}&tileRow={y}&geokey=2CA54B6D242305ABF3822EC38D121CD9',
					projection: projection_4490,
					maxZoom: 18
				})
			});
			const fxpcSatelliteRoadSignLayer = new ol.layer.Tile({
				source: new ol.source.XYZ({
					url: 'https://fxpc.mem.gov.cn/data_preparation/a12eadf6-1a57-43fe-9054-2e22277bd553/83e5b643-edc3-4118-ba04-2a9186606b42/wmts?layer=cia&style=default&tileMatrixSet=c&service=wmts&request=gettile&version=1.0.0&format=tiles&tileMatrix={z}&tileCol={x}&tileRow={y}&geokey=2CA54B6D242305ABF3822EC38D121CD9',
					projection: projection_4490,
					maxZoom: 18
				})
			});

			const source = new ol.source.Vector();

			const polygonStyle = { // 多边形样式
				fillColor: '#409EFF', // 填充色
				fillOpacity: 0.2, // 填充透明度
				strokeColor: '#ffff00', // 轮廓颜色
				// strokeColor: '#409EFF', // 轮廓颜色
				strokeWeight: 1, // 轮廓宽度
				strokeOpacity: 0.9 // 轮廓透明度
			};
			const vector = new ol.layer.Vector({
				source: source,
				zIndex: 4
			});
			const GDMap = new ol.Map({
				target: 'map',
				controls: ol.control.defaults({
					zoom: false
				}),
				layers: [
					// gdLayer
					fxpcSatelliteLayer,
					fxpcSatelliteRoadSignLayer,
					vector
				],
				view: new ol.View({
					// center: [13087853.731100908, 3652314.085522261],
					center: ol.proj.transform([116.1733, 31.9137], "EPSG:4326", "EPSG:4490"),
					zoom: 14,
					// resolutions: [156543.03392804076, 78271.51696402022, 39135.75848201011, 19567.879241005117, 9783.939620502542, 4891.969810251271, 2445.9849051256383, 1222.9924525628178, 611.4962262814075, 305.7481131407024, 152.8740565703523, 76.43702828517615, 38.21851414258808, 19.10925707129404, 9.55462853564699, 4.777314267823495, 2.388657133911756, 1.1943285669558765, 0.5971642834779383, 0.29858214173896913, 0.14929107086948457, 0.07464553543474216, 0.03732276771737108, 0.018661383858685567, 0.009330691929342784],
					// projection: 'EPSG:3857',
					// extent: [-20037508.34, -20037508.345578436, 20037508.345578436, 20037508.34]
					resolutions: resolutions_4490,
					projection: projection_4490,
				})
			});
			// fetch('http://192.168.31.235:48080/admin-api/farmer/contract-land/listall', {
			// 	method: 'get',
			// 	headers: {
			// 		'Authorization': 'Bearer abdac0e0f1814c3d8da08d37e14fc435',
			// 		'tenant-id': '1',
			// 	}
			// }).then(function(response) {
			// 	return response.json()
			// }).then((json) => {})

			const polygons = [];
			// var list = [{
			// 		blockIds: null,
			// 		circulationStatus: null,
			// 		contractFarmerId: 15,
			// 		contractorCode: null,
			// 		coordinates: [
			// 			[116.15600296601681, 31.924511664133313],
			// 			[116.15630108079237, 31.92439501052548],
			// 			[116.1563529268403, 31.924399331029466],
			// 			[116.15638533062027, 31.924418773297447],
			// 			[116.15640909339223, 31.92438420926549],
			// 			[116.15637452936029, 31.924321561957573],
			// 			[116.15642205490421, 31.92431508120159],
			// 			[116.15654302901605, 31.9243777285095],
			// 			[116.15681090026366, 31.924494382117338],
			// 			[116.15684546429564, 31.924528946149284],
			// 			[116.15685626555562, 31.92457647169322],
			// 			[116.15679577849968, 31.924647760009123],
			// 			[116.15685626555562, 31.924719048325024],
			// 			[116.15696211790346, 31.924788176388926],
			// 			[116.15704204722735, 31.924820580168884],
			// 			[116.15674825295577, 31.925159739732415],
			// 			[116.15615418365658, 31.9248810672248],
			// 			[116.15631404230436, 31.924626157489154],
			// 			[116.15600296601681, 31.924511664133313]
			// 		],
			// 		createTime: null,
			// 		cropsType: 2,
			// 		eastTo: null,
			// 		farmerLandId: null,
			// 		farmerLandList: null,
			// 		id: 48,
			// 		isBasicFarmland: 1,
			// 		isMortgage: null,
			// 		isPublic: null,
			// 		landArea: 7,
			// 		landCode: "12",
			// 		landName: "徐前福承包的地块",
			// 		northTo: null,
			// 		southTo: null,
			// 		status: null,
			// 		westTo: null
			// 	}, {
			// 		blockIds: null,
			// 		circulationStatus: null,
			// 		contractFarmerId: 15,
			// 		contractorCode: null,
			// 		coordinates: [
			// 			[116.15600296601681, 31.924511664133313],
			// 			[116.15630108079237, 31.92439501052548],
			// 			[116.1563529268403, 31.924399331029466],
			// 			[116.15638533062027, 31.924418773297447],
			// 			[116.15640909339223, 31.92438420926549],
			// 			[116.15637452936029, 31.924321561957573],
			// 			[116.15642205490421, 31.92431508120159],
			// 			[116.15654302901605, 31.9243777285095],
			// 			[116.15681090026366, 31.924494382117338],
			// 			[116.15684546429564, 31.924528946149284],
			// 			[116.15685626555562, 31.92457647169322],
			// 			[116.15679577849968, 31.924647760009123],
			// 			[116.15685626555562, 31.924719048325024],
			// 			[116.15696211790346, 31.924788176388926],
			// 			[116.15704204722735, 31.924820580168884],
			// 			[116.15674825295577, 31.925159739732415],
			// 			[116.15615418365658, 31.9248810672248],
			// 			[116.15631404230436, 31.924626157489154],
			// 			[116.15600296601681, 31.924511664133313]
			// 		],
			// 		createTime: null,
			// 		cropsType: 2,
			// 		eastTo: null,
			// 		farmerLandId: null,
			// 		farmerLandList: null,
			// 		id: 49,
			// 		isBasicFarmland: 1,
			// 		isMortgage: null,
			// 		isPublic: null,
			// 		landArea: 17,
			// 		landCode: "11",
			// 		landName: "徐前福承包的地块",
			// 		northTo: null,
			// 		southTo: null,
			// 		status: null,
			// 		westTo: null
			// 	},
			// 	{
			// 		blockIds: null,
			// 		circulationStatus: null,
			// 		contractFarmerId: 15,
			// 		contractorCode: null,
			// 		coordinates: [
			// 			[116.15899678269112, 31.92631098984815],
			// 			[116.15898310339736, 31.926128599264732],
			// 			[116.15903326080779, 31.926051083266778],
			// 			[116.15905149986614, 31.925809415743746],
			// 			[116.15910621704118, 31.925859573154185],
			// 			[116.15924756974331, 31.925859573154185],
			// 			[116.15944819938507, 31.925982686797994],
			// 			[116.15927948809541, 31.92619699573351],
			// 			[116.15926580880163, 31.92634746796483],
			// 			[116.15916549398078, 31.926324669141906],
			// 			[116.15903782057238, 31.92637026678776],
			// 			[116.15899678269112, 31.92631098984815]
			// 		],
			// 		createTime: null,
			// 		cropsType: 2,
			// 		eastTo: null,
			// 		farmerLandId: null,
			// 		farmerLandList: null,
			// 		id: 50,
			// 		isBasicFarmland: 1,
			// 		isMortgage: null,
			// 		isPublic: null,
			// 		landArea: 4,
			// 		landCode: "10",
			// 		landName: "徐前福承包的地块",
			// 		northTo: null,
			// 		southTo: null,
			// 		status: null,
			// 		westTo: null
			// 	}
			// ]

			const list = getQuery('data');
			if (list instanceof Array) {
				list.forEach(data => {
					const polygon = {
						id: data.id,
						path: data.coordinates,
						landCode: data.landCode,
						landName: data.landName,
						landArea: data.landArea
						// cropsType: getDictData(DICT_TYPE.FARMER_CROPS_TYPE, data.cropsType)['label'],
						// circulationStatus: getDictData(DICT_TYPE.FARMER_LAND_CIRCULATION_STATUS, data.circulationStatus)['label'],
						// isBasicFarmland: getDictData(DICT_TYPE.SYSTEM_IS_TYPE, data.isBasicFarmland)['label']
					};
					addPolygon(polygon)
				})
			} else {
				const polygon = {
					id: list.id,
					path: list.coordinates,
					landCode: list.landCode,
					landName: list.landName,
					landArea: list.landArea
					// cropsType: getDictData(DICT_TYPE.FARMER_CROPS_TYPE, data.cropsType)['label'],
					// circulationStatus: getDictData(DICT_TYPE.FARMER_LAND_CIRCULATION_STATUS, data.circulationStatus)['label'],
					// isBasicFarmland: getDictData(DICT_TYPE.SYSTEM_IS_TYPE, data.isBasicFarmland)['label']
				};
				addPolygon(polygon)
			}

			focusFeatureCenter()
			initEvent()

			function initEvent() {
				GDMap.on('click', (ev) => {
					GDMap.forEachFeatureAtPixel(ev.pixel, (feature) => {
						feature.dispatchEvent({
							type: 'click',
							event: ev
						})
					})
				})
			}

			// 地图上添加单个多边形
			function addPolygon(polygon, operability = true) {
				const path = polygon.path
				if (path.length === 0) {
					//console.log("多边形没有经纬度信息")
					return false
				}

				const coordinatesPolygon = new Array();
				path.forEach((v) => {
					// var pointTransform = fromLonLat(v, "EPSG:3857");
					const pointTransform = ol.proj.transform(v, "EPSG:4326", "EPSG:4490");
					coordinatesPolygon.push(pointTransform);
				})
				const polygonFeature = new ol.Feature({
					geometry: new ol.geom.Polygon([coordinatesPolygon])
				})

				// 设置extData数据，可通过getProperties获取
				polygonFeature.setProperties({
					extData: polygon
				})

				// 设置样式
				if (polygon.styles && Object.keys(polygon.styles).length > 0) {
					polygonSetStyle(polygonFeature, polygon.styles)
					polygonFeature.setProperties({
						styles: polygon.styles
					})
				} else {
					polygonSetStyle(polygonFeature, polygonStyle)
					polygonFeature.setProperties({
						styles: polygonStyle
					})
				}
				// 设置id
				polygonFeature.setId(polygon.id)
				// 添加到地图显示
				vector.getSource().addFeature(polygonFeature)

				if (operability) {
					polygons.push(polygon)
					// 添加点击事件
					document.addEventListener('UniAppJSBridgeReady', function() {
						uni.getEnv(function(res) {
							console.log('当前环境：' + JSON.stringify(res));
						});

						polygonFeature.on('click', function(ev) {
							console.log(88)
							console.log(ev.target.getProperties().extData.id)
							uni.postMessage({
								data: {
									id: ev.target.getProperties().extData.id
								}
							});
						})
					});
				}
			}
			// 设置多边形样式，默认是添加样式，type为edit的时候为编辑样式，多边形角有圆点
			function polygonSetStyle(feature, styles, type = 'add') {
				const fill = new ol.style.Fill({
					color: hexToRgba(styles.fillColor, styles.fillOpacity)
				})
				const stroke = new ol.style.Stroke({
					color: hexToRgba(styles.strokeColor, styles.strokeOpacity),
					width: styles.strokeWeight
				})
				const style = new ol.style.Style({
					fill,
					stroke
				})
				const circleStyle = new ol.style.Style({
					image: new ol.style.Circle({
						radius: 3,
						fill: new ol.style.Fill({
							color: '#409EFF'
						})
					}),
					geometry: () => {
						const coordinates = feature.getGeometry().getCoordinates()[0]
						return new MultiPoint(coordinates)
					}
				})
				if (type === 'add') {
					feature.setStyle(style)
				} else {
					feature.setStyle([style, circleStyle])
				}
			}

			function hexToRgba(hex, trans = 1) {
				let hexColor = /^#/.test(hex) ? hex.slice(1) : hex
				let r
				let g
				let b
				hexColor = /^[0-9a-f]{3}|[0-9a-f]{6}$/i.test(hexColor) ? hexColor : 'fffff'
				if (hexColor.length === 3) {
					hexColor = hexColor.replace(/(\w)(\w)(\w)/gi, '$1$1$2$2$3$3')
				}
				r = hexColor.slice(0, 2)
				g = hexColor.slice(2, 4)
				b = hexColor.slice(4, 6)
				r = parseInt(r, 16)
				g = parseInt(g, 16)
				b = parseInt(b, 16)
				return `rgba(${r}, ${g}, ${b}, ${trans})`
			}
			// 聚焦到多边形要素位置
			function focusFeatureCenter() {

				const viewer = GDMap.getView();
				const features = source.getFeatures();
				if (features.length > 0) {

					const center = getFeatureCenter(features[0])

					viewer.animate({
						center: center,
						zoom: 16,
						duration: 500 // 动画时长
					})

				}

			}
			// 获取多边形要素的中心坐标
			function getFeatureCenter(feature) {
				const polygonGeometry = feature.getGeometry()
				const path = polygonGeometry.getCoordinates()[0] // 获取多边形的path
				const center = ol.extent.getCenter(ol.extent.boundingExtent(path)) // 获取多边形的中心坐标
				return center
			}
		</script>
	</body>
</html>
